/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.modules.storage.entity.Goods;
import com.jeesite.modules.storage.entity.GoodsSpec;
import com.jeesite.modules.storage.service.BrandService;
import com.jeesite.modules.storage.service.CategoryService;
import com.jeesite.modules.storage.service.GoodsService;
import com.jeesite.modules.storage.service.GoodsSpecService;
import com.jeesite.modules.storage.util.WebUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 商品Controller
 */
@Controller(value = "webgoods")
@RequestMapping(value = "${adminPath}/storage/goods")
public class GoodsController extends BaseController {

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsSpecService goodsSpecService;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private BrandService brandService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Goods get(String id, boolean isNewRecord) {
		return goodsService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequestMapping(value = {"list", ""})
	public String list(Goods goods, Model model) {
		model.addAttribute("goods", goods);
		model.addAttribute("brands", brandService.getAllList());
		model.addAttribute("categoies", categoryService.getAllList());
		return "modules/storage/goods/list";
	}

	/**
	 * 选择
	 */
	@RequestMapping(value = {"select", ""})
	public String select(Goods goods, String[] goodsIdList, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (JsonMapper.fromJson(selectDataJson, Map.class) != null){
			model.addAttribute("selectData", selectDataJson);
		}else if(goodsIdList != null){
			Map map= new HashMap();
			for (String goodsId :goodsIdList){
				Goods item = goodsService.get(goodsId);
				map.put(item.getId(),item);
			}
			model.addAttribute("selectData",JsonMapper.toJson(map));
		}
		model.addAttribute("goods", goods);
		model.addAttribute("brands", brandService.getAllList());
		model.addAttribute("categoies", categoryService.getAllList());
		return "modules/storage/goods/select";
	}

	/**
	 * 查询列表数据
	 */
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Goods> listData(Goods goods, HttpServletRequest request, HttpServletResponse response) {
		goods.setPage(new Page<>(request, response));
		Page<Goods> page = goodsService.findPage(goods);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequestMapping(value = "form")
	public String form(Goods goods, Model model) {
		model.addAttribute("goods", goods);
		model.addAttribute("brands", brandService.getAllList());
		model.addAttribute("categoies", categoryService.getAllList());
		return "modules/storage/goods/form";
	}

	/**
	 * 保存商品
	 */
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Goods goods) {
		try{
			if(StringUtils.isNotBlank(goods.getPicture()) && goods.getPicture().split("\\|").length < 4){
				return renderResult(Global.FALSE, text("素材至少4张以上"));
			}
			goodsService.save(goods);
			return renderResult(Global.TRUE, text("保存商品成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}
	
	/**
	 * 删除商品
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Goods goods) {
		try{
			goodsService.delete(goods);
			return renderResult(Global.TRUE, text("删除商品成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}

	/**
	 * 导出数据
	 */
	@RequestMapping(value = "exportData")
	public void exportData(HttpServletResponse response) {

	}

	/**
	 * 下载导入数据模板
	 */
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		importTemplate(response,"商品 - 大仓库.xlsx");
	}

	/*
	 * 读取Excel到列表
	 */
	private List<Goods> readExcelToList(MultipartFile file){
		try {
			List<Goods> goodsList = new ArrayList<>();
			Workbook workbook = getWorkbook(file);
			Sheet sheet = workbook.getSheetAt(0);
			Goods goods = null;
			for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row row = sheet.getRow(rowNum);
				if (row == null  || row.getLastCellNum() < 20) {
					continue;
				}
				String code = getCellValue(row,3);
				if(StringUtils.isBlank(code)){
					continue;
				}
				Boolean isNew = goods == null || !goods.getCode().equals(code);
				if(isNew){
					goods = new Goods();
					goods.setBrandId(getCellValue(row,0));
					goods.setCateId(getCellValue(row,1));
					goods.setThumbnail(getCellValue(row,2));
					goods.setCode(code);
					goods.setPlatform(getCellValue(row,4));
					goods.setName(getCellValue(row,5));
					goods.setCategory(getCellValue(row,6));
					goods.setYear(getCellValue(row,7));
					goods.setSeason(getCellValue(row,8));
					goods.setPlace(getCellValue(row,9));
					goods.setMaterial(getCellValue(row,10));
					goods.setPicture(getCellValue(row,12));
					goods.setGoodsSpecList(new ArrayList<>());
				}
				GoodsSpec goodsSpec = new GoodsSpec();
				goodsSpec.setSort(goods.getGoodsSpecList().size() + 1);
				goodsSpec.setColor(getCellValue(row,11));
				goodsSpec.setCode(getCellValue(row,14));
				goodsSpec.setName(getCellValue(row,13));
				goodsSpec.setPrice(Double.parseDouble(getCellValue(row,15)));
				goodsSpec.setMemberPrice(Double.parseDouble(getCellValue(row,16)));
				goodsSpec.setVipPrice(Double.parseDouble(getCellValue(row,17)));
				goodsSpec.setAgentPrice(Double.parseDouble(getCellValue(row,18)));
				goodsSpec.setRemarks(getCellValue(row,19));
				goods.getGoodsSpecList().add(goodsSpec);
				if(isNew){
					goodsList.add(goods);
				}
			}
			return goodsList;
		} catch (Exception ex) {
			throw ex;
		}
	}

	/*
	 * 读取Excel到列表
	 */
	private String check(List<Goods> goodsList){
		StringBuilder stringBuilder = new StringBuilder();
		for (Goods goods : goodsList) {
			if(StringUtils.isBlank(brandService.getIdByName(goods.getBrandId()))){
				stringBuilder.append(goods.getBrandId() + "未找到对应品牌\r\n");
			}
			if(StringUtils.isBlank(categoryService.getIdByName(goods.getCateId()))){
				stringBuilder.append(goods.getCateId() + "未找到对应分类\r\n");
			}
		}
		return stringBuilder.toString();
	}

	/**
	 * 导入数据
	 */
	@ResponseBody
	@PostMapping(value = "importData")
	public String importData(MultipartFile file) {
		try {
			List<Goods> goodsList = readExcelToList(file);
			String msg = check(goodsList);
			if(StringUtils.isNotBlank(msg)){
				return renderResult(Global.FALSE, "导入出错:" + msg);
			}
			for (Goods goods : goodsList){
				goods.setId(goodsService.getIdByCode(goods.getCode()));
				goods.setBrandId(brandService.getIdByName(goods.getBrandId()));
				goods.setCateId(categoryService.getIdByName(goods.getCateId()));
				if(StringUtils.isNotBlank(goods.getThumbnail())){
					goods.setThumbnail("/userfiles/goods/" + goods.getCode() + "/" + goods.getThumbnail());
				}
				String picture = goods.getPicture();
				if(StringUtils.isNotBlank(picture)){
					List<String> pictures = new ArrayList<>();
					for (String pic : picture.split(",")){
						pictures.add("/userfiles/goods/" + goods.getCode() + "/" + pic);
					}
					goods.setPicture(String.join("|",pictures));
				}
				for (GoodsSpec goodsSpec : goods.getGoodsSpecList()){
					goodsSpec.setGoodsId(goods.getId());
					GoodsSpec dbGoodsSpec = goodsSpecService.getByCode(goodsSpec.getCode());
					if(dbGoodsSpec!=null){
						goodsSpec.setId(goodsSpec.getId());
					}
				}
				goodsService.save(goods);
			}
			return renderResult(Global.TRUE,"导入成功");
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "导入出错:" + ex.getMessage());
		}
	}
}